package top.conangao.uaa.service;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import top.conangao.common.constant.CommonConstants;
import top.conangao.common.holder.UserContextHolder;
import top.conangao.common.security.domain.SecurityUser;
import top.conangao.uaa.domain.SysUser;

import java.util.List;

/**
 * @author ConanGao
 * @since 1.0
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SysUserService sysUserService;
    private final SysMenuService sysMenuService;
    private final SysRoleService sysRoleService;
    private final HttpServletRequest request;
    private final RocketMQTemplate rocketMQTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        init();
        // 查询用户
        SysUser one = sysUserService.lambdaQuery().eq(SysUser::getUsername, username).one();
        Assert.notNull(one,"账号不存在");
        // 合并角色权限
        List<String> permissions = sysMenuService.getPermissionsByUserId(one.getId());
        sysRoleService.getRolesByUserId(one.getId()).forEach(role->permissions.add("ROLE_"+role));
        // 组装自定义UserDetails
        SecurityUser user = new SecurityUser();
        user.setId(one.getId());
        user.setUsername(one.getUsername());
        user.setTenantId(one.getTenantId());
        user.setDeptId(one.getDeptId());
        user.setPassword(one.getPassword());
        user.setSuperadmin(one.getSuperadmin());
        user.setPermissions(permissions);
        // 发送登录成功消息
        rocketMQTemplate.convertAndSend("topic_test:tagA","发送了登录成功消息");
        return user;
    }
    
    private void init(){
        // 额外获取租户参数
        String tenantId = request.getParameter(CommonConstants.TENANTCOLUMN);
        // mybatisplus参数tenantId需要用到
        UserContextHolder.User _user = UserContextHolder.get();
        _user.setTenantId(Long.parseLong(tenantId));
        UserContextHolder.set(_user);
    }
}
